import * as shop from '@/api/shop'
const state = {
  name: 'cart',
  carts: [],
  // 结算状态: null / success / failed
  checkoutStatus: null
}
const mutations = {
  incrementItemQuantity (state, playload) { // 商品已经存在在购物车
    const item = state.carts.find(el => el.id === playload.id)
    item.quantity++
  },
  pushProductToCart (state, playload) { // 商品不存在在购物车
    state.carts.push({
      id: playload.id,
      quantity: 1
    })
  },
  setCheckoutStatus (state, status) {
    state.checkoutStatus = status
  },
  setCart (state, playload) {
    state.carts = playload
  }
}
const getters = {
  cartProduct (state, getters, rootState) { // 根据state中的数据, 组合数据展示
    return state.carts.map(el => {
      const prod = rootState.products.all.find(item => item.id === el.id)
      return {
        id: el.id,
        title: prod.title,
        quantity: el.quantity,
        price: prod.price
      }
    })
  },
  totalPrice (state, getters) {
    return getters.cartProduct.reduce((result, now) => {
      return result + now.price * now.quantity
    }, 0)
  }
}
const actions = {
  checkout ({ state, commit }, products) {
    // 备份购物车数据
    const savedCartPorducts = [...products]
    // 清除支付状态
    commit('setCheckoutStatus', null)
    // 清空购物车
    commit('setCart', [])
    // 发起结算请求
    //  - 成功 设置成功状态
    //  - 失败 设置失败状态, 回滚购物车数据
    shop.bugProduct(
      products,
      () => {
        commit('setCheckoutStatus', 'successful')
      },
      () => {
        commit('setCheckoutStatus', 'failed')
        commit('setCart', savedCartPorducts)
      }
    )
  },
  addProductToCart ({ state, commit }, product) {
    // 判断商品是否有库存
    if (product.inventory) {
      const cartItem = state.carts.find(el => el.id === product.id)
      if (cartItem) {
        commit({
          type: 'incrementItemQuantity',
          id: product.id
        })
      } else { // 如果没有找到该商品, 重新添加
        commit({
          type: 'pushProductToCart',
          id: product.id
        })
      }
    } else {
      alert('该商品已经没库存了...')
    }
    // 如果在该模块操作其他模块, 需要在 添加 { root:true }
    commit({
      type: 'products/decrementProductInventory', // 默认在当前模块查找
      id: product.id
    }, { root: true })
  }
}

export default {
  namespaced: true, // 开启命名空间W
  state,
  mutations,
  getters,
  actions
}
